package com.xyxy.platform.website.member.web.controller;

import com.google.common.collect.ImmutableMap;
import com.xyxy.platform.modules.core.beanvalidator.BeanValidators;
import com.xyxy.platform.modules.core.cache.memcached.SpyMemcachedClient;
import com.xyxy.platform.modules.core.file.SystemFileService;
import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.core.utils.IpUtils;
import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.controller.BaseController;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import com.xyxy.platform.modules.entity.image.ImageItem;
import com.xyxy.platform.modules.entity.image.ImageType;
import com.xyxy.platform.modules.entity.image.ImageTypes;
import com.xyxy.platform.modules.entity.member.Member;
import com.xyxy.platform.modules.entity.member.MemberLoginLog;
import com.xyxy.platform.modules.service.common.exception.SmsException;
import com.xyxy.platform.modules.service.common.sms.SmsService;
import com.xyxy.platform.modules.service.common.sms.vo.SmsTemplateType;
import com.xyxy.platform.modules.service.image.ImageItemService;
import com.xyxy.platform.modules.service.member.MemberLoginLogService;
import com.xyxy.platform.modules.service.member.MemberService;
import com.xyxy.platform.website.common.constants.AppConstants;
import com.xyxy.platform.website.common.web.jcaptcha.JCaptcha;
import com.xyxy.platform.website.common.vo.CurrentLoginUser;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Validator;
import java.util.Date;
import java.util.List;

/**
 * Created by VirtueCai on 15/12/15.
 */
@Controller
public class AuthorizationController extends BaseController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberLoginLogService loginLogService;
    @Autowired
    private Validator validator;
    @Autowired
    private SmsService smsService;
    @Autowired
    private SpyMemcachedClient memcachedClient;
    @Autowired
    private ImageItemService imageItemService;
    @Autowired
    private SystemFileService systemFileService;

    @RequestMapping(value = "register", method = RequestMethod.GET)
    public String registerView() {
        return "public/register";
    }

    @RequestMapping(value = "regnovalidata", method = RequestMethod.GET)
    public String regnovalidata() {
        return "public/regnovalidata";
    }

    @ResponseBody
    @RequestMapping(value = "regnovalidata", method = RequestMethod.POST)
    public ResponseMessage<?> regnovalidata(Member member) {
        Long code = memcachedClient.get(member.getMobile());
        if (memberService.exist(member.getMobile())) {
            return ResponseUtils.jsonFail("该手机号码已被注册!请直接登录");
        }
        memberService.register(member);
        return ResponseUtils.jsonResult(member, true, "注册成功");
    }


    @RequestMapping(value = "loginnovalidata", method = RequestMethod.GET)
    public String loginnovalidata() {
        return "public/loginnovalidata";
    }


    @ResponseBody
    @RequestMapping(value = "loginnovalidata", method = RequestMethod.POST)
    public ResponseMessage<?> loginnovalidata(MemberForm memberform) {
        //表单验证
        BeanValidators.validateWithException(validator, memberform);

        boolean verifyCode = JCaptcha.validateResponse(request, memberform.getJcaptcha());
        if (!verifyCode) {
            return ResponseUtils.jsonFail("验证码错误");
        }

        //记录登陆日志
        MemberLoginLog log = new MemberLoginLog();
        log.setLoginIp(IpUtils.getIpAddr(request));
        log.setLoginTime(new Date());
        Member member = null;
        try {
            member = memberService.login(memberform.getMoblie(), memberform.getPassword());
        } catch (Exception e) {
            logger.error("登录失败，e: {}", e.getMessage());
        }
        if (null != member) {
            log.setIsSuccess(1);
            log.setMemberId(member.getId());
            //记录登陆日志
            loginLogService.createLoginLog(log);
        } else {
            log.setIsSuccess(0);
            //记录登陆日志
            loginLogService.createLoginLog(log);
            return ResponseUtils.jsonFail("用户名或密码错误，登录失败");
        }


        // 存储 session
        // 会员头像
        String imageUrl = null;
        if (null != member.getImagePkgId()) {
            List<ImageItem> imageItemList = imageItemService.findImageItemList(member.getImagePkgId(), ImageTypes.USER_ICON);
            ImageItem imageItem = Collections3.getFirst(imageItemList);
            if (null != imageItem) imageUrl = systemFileService.getFileUrlByUri(imageItem.getUri());
        }
        String currentLoginUserName = StringUtils.isEmpty(member.getAlias()) ? member.getUserName() : member.getAlias();
        request.getSession().setAttribute(AppConstants.CURRENT_USER, new CurrentLoginUser(member.getId(), currentLoginUserName, imageUrl));

        //跳转链接
        String loginSuccessUrl = (String) request.getSession().getAttribute(AppConstants.LOGIN_SUCCESS_REDIRECT_URL);
        request.getSession().removeAttribute(AppConstants.LOGIN_SUCCESS_REDIRECT_URL);
        String redirectUrl = loginSuccessUrl == null ? "/" : loginSuccessUrl;
        return ResponseUtils.jsonSuccess(ImmutableMap.of("redirectUrl", redirectUrl));
    }





    @ResponseBody
    @RequestMapping(value = "biewanlecode", method = RequestMethod.GET)
    public ResponseMessage<?> getcode(@RequestParam String moblie) {
        //获取ip地址
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        try {
            smsService.sendRegisterCode(moblie, ip);
        } catch (SmsException e) {
            String msg="";
            switch (e.getCode()){
                case 1:
                    msg="过多注册，请明天再试";
                    break;
                case 2:
                    msg="已超过获取次数限制，请明天再试";
                    break;
                case 3:
                    msg="验证码尚未过期，请勿重试";
                    break;
            }
            return ResponseUtils.jsonFail(msg);
        }
        return ResponseUtils.jsonSuccess(true);
    }

    @ResponseBody
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ResponseMessage<?> register(Member member, String vcode) {
        Long code = memcachedClient.get(member.getMobile());
        if (code == null) {
            return ResponseUtils.jsonFail("请获取验证码以后再进行注册");
        } else if (!code.toString().equals(vcode)) {
            return ResponseUtils.jsonFail("请输入正确的短信验证码");
        }
        if (memberService.exist(member.getMobile())) {
            return ResponseUtils.jsonFail("该手机号码已被注册!请直接登录");
        } else {
            memberService.register(member);
        }
        //记录登陆日志
        MemberLoginLog log = new MemberLoginLog();
        log.setLoginIp(IpUtils.getIpAddr(request));
        log.setLoginTime(new Date());
        log.setIsSuccess(1);
        log.setMemberId(member.getId());
        loginLogService.createLoginLog(log);
        try {
            member=memberService.login(member.getMobile(),member.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String currentLoginUserName = StringUtils.isEmpty(member.getAlias()) ? member.getUserName() : member.getAlias();
        request.getSession().setAttribute(AppConstants.CURRENT_USER, new CurrentLoginUser(member.getId(), currentLoginUserName, ""));
        return ResponseUtils.jsonResult(member, true, "注册成功");
    }


    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String loginView() {
        return "public/login";
    }

    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ResponseMessage<?> login(MemberForm memberform) {
        //表单验证
        BeanValidators.validateWithException(validator, memberform);

        boolean verifyCode = JCaptcha.validateResponse(request, memberform.getJcaptcha());
        if (!verifyCode) {
            return ResponseUtils.jsonFail("验证码错误");
        }

        //记录登陆日志
        MemberLoginLog log = new MemberLoginLog();
        log.setLoginIp(IpUtils.getIpAddr(request));
        log.setLoginTime(new Date());
        Member member = null;
        try {
            member = memberService.login(memberform.getMoblie(), memberform.getPassword());
        } catch (Exception e) {
            logger.error("登录失败，e: {}", e.getMessage());
        }
        if (null != member) {
            log.setIsSuccess(1);
            log.setMemberId(member.getId());
            //记录登陆日志
            loginLogService.createLoginLog(log);
        } else {
            log.setIsSuccess(0);
            //记录登陆日志
            loginLogService.createLoginLog(log);
            return ResponseUtils.jsonFail("用户名或密码错误，登录失败");
        }


        // 存储 session
        // 会员头像
        String imageUrl = null;
        if (null != member.getImagePkgId()) {
            List<ImageItem> imageItemList = imageItemService.findImageItemList(member.getImagePkgId(), ImageTypes.USER_ICON);
            ImageItem imageItem = Collections3.getFirst(imageItemList);
            if (null != imageItem) imageUrl = systemFileService.getFileUrlByUri(imageItem.getUri());
        }
        String currentLoginUserName = StringUtils.isEmpty(member.getAlias()) ? member.getUserName() : member.getAlias();
        request.getSession().setAttribute(AppConstants.CURRENT_USER, new CurrentLoginUser(member.getId(), currentLoginUserName, imageUrl));

        //跳转链接
        String loginSuccessUrl = (String) request.getSession().getAttribute(AppConstants.LOGIN_SUCCESS_REDIRECT_URL);
        request.getSession().removeAttribute(AppConstants.LOGIN_SUCCESS_REDIRECT_URL);
        String redirectUrl = loginSuccessUrl == null ? "/" : loginSuccessUrl;
        return ResponseUtils.jsonSuccess(ImmutableMap.of("redirectUrl", redirectUrl));
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/login";
    }

    @ResponseBody
    @RequestMapping(value = "/checkmobile")
    public boolean checkmobile(String mobile) {
        return memberService.exist(mobile);
    }

}

class MemberForm {
    @NotEmpty
    private String moblie;

    @NotEmpty
    private String password;

    @NotEmpty
    private String jcaptcha;


    public String getJcaptcha() {
        return jcaptcha;
    }

    public void setJcaptcha(String jcaptcha) {
        this.jcaptcha = jcaptcha;
    }

    public String getMoblie() {
        return moblie;
    }

    public void setMoblie(String moblie) {
        this.moblie = moblie;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}